<template>
  <NDrawer v-model:show="visible" :width="900" title="清洗结果">
    <NDrawerContent closable>
      <NSpin :show="loading">
        <NSpace vertical :size="16">
          <!-- 统计信息 -->
          <NCard title="清洗统计" size="small">
            <NGrid :cols="4" :x-gap="12">
              <NGridItem>
                <NStatistic label="处理记录数" :value="result?.processedCount || 0" />
              </NGridItem>
              <NGridItem>
                <NStatistic label="清洗记录数" :value="result?.cleanedCount || 0" />
              </NGridItem>
              <NGridItem>
                <NStatistic label="清洗率" :value="cleanRate" suffix="%" />
              </NGridItem>
              <NGridItem>
                <NStatistic label="执行时长" :value="result?.executionTime || 0" suffix="ms" />
              </NGridItem>
            </NGrid>
          </NCard>

          <!-- 清洗前后对比 -->
          <NCard title="清洗效果对比" size="small">
            <div ref="chartRef" style="width: 100%; height: 300px"></div>
          </NCard>

          <!-- 清洗详情 -->
          <NCard title="清洗详情" size="small">
            <NDataTable
              :columns="detailColumns"
              :data="result?.cleanDetails || []"
              size="small"
              :max-height="400"
              :pagination="{ pageSize: 10 }"
            />
          </NCard>

          <!-- 备份信息 -->
          <NCard v-if="result?.backupInfo" title="备份信息" size="small">
            <NDescriptions :column="2" label-placement="left">
              <NDescriptionsItem label="备份表">{{ result.backupInfo.backupTable }}</NDescriptionsItem>
              <NDescriptionsItem label="备份时间">{{ result.backupInfo.backupTime }}</NDescriptionsItem>
              <NDescriptionsItem label="备份记录数">{{ result.backupInfo.backupCount }}</NDescriptionsItem>
              <NDescriptionsItem label="可回滚">
                <NTag :type="result.backupInfo.canRollback ? 'success' : 'error'">
                  {{ result.backupInfo.canRollback ? '是' : '否' }}
                </NTag>
              </NDescriptionsItem>
            </NDescriptions>
          </NCard>
        </NSpace>
      </NSpin>
    </NDrawerContent>
  </NDrawer>
</template>

<script setup lang="ts">
import { computed, ref, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import type { ECharts } from 'echarts';
import { fetchCleanTaskDetail } from '@/service/api';

interface Props {
  visible: boolean;
  taskId: number;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  taskId: 0
});

interface Emits {
  (e: 'update:visible', visible: boolean): void;
}

const emit = defineEmits<Emits>();

const visible = computed({
  get: () => props.visible,
  set: val => emit('update:visible', val)
});

const loading = ref(false);
const result = ref<any>(null);
const chartRef = ref<HTMLElement>();
let chartInstance: ECharts | null = null;

const cleanRate = computed(() => {
  if (!result.value || !result.value.processedCount) return 0;
  return ((result.value.cleanedCount / result.value.processedCount) * 100).toFixed(2);
});

const detailColumns = [
  { key: 'rowId', title: '记录ID', width: 100 },
  { key: 'ruleName', title: '应用规则', width: 150 },
  { key: 'fieldName', title: '清洗字段', width: 120 },
  { key: 'beforeValue', title: '清洗前', width: 150 },
  { key: 'afterValue', title: '清洗后', width: 150 },
  { key: 'cleanType', title: '清洗类型', width: 120 }
];

async function loadResult() {
  if (!props.taskId) return;
  loading.value = true;
  try {
    const res = await fetchCleanTaskDetail(props.taskId);
    result.value = res.data.lastResult || {
      processedCount: 0,
      cleanedCount: 0,
      executionTime: 0,
      cleanDetails: [],
      dimensionStats: {},
      backupInfo: null
    };
    await nextTick();
    renderChart();
  } finally {
    loading.value = false;
  }
}

function renderChart() {
  if (!chartRef.value || !result.value) return;

  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }

  const dimensionStats = result.value.dimensionStats || {};
  const categories = Object.keys(dimensionStats);
  const beforeData = categories.map(key => dimensionStats[key].before || 0);
  const afterData = categories.map(key => dimensionStats[key].after || 0);

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['清洗前', '清洗后']
    },
    xAxis: {
      type: 'category',
      data: categories
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '清洗前',
        type: 'bar',
        data: beforeData,
        itemStyle: {
          color: '#f56c6c'
        }
      },
      {
        name: '清洗后',
        type: 'bar',
        data: afterData,
        itemStyle: {
          color: '#67c23a'
        }
      }
    ]
  };

  chartInstance.setOption(option);
}

watch(visible, val => {
  if (val) {
    loadResult();
  } else {
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
  }
});
</script>

<style scoped></style>
